package com.baoleme.handle;


import com.baoleme.common.Result;
import com.baoleme.exceptions.BusinessException;
import com.baoleme.exceptions.enumeration.ResponseEnum;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice //增强控制层注解
public class BaseExceptionHandler {
    /*对自定义异常进行一个处理，使用统一输出格式进行处理*/
    @ExceptionHandler
    public Object handleException(Exception e) {
        e.printStackTrace();
        return Result.error(ResponseEnum.ERROR);
    }

    @ExceptionHandler(BusinessException.class)
    public Object handleBusinessException(BusinessException e) {
        return Result.error(e.getResponse());
    }

    @ExceptionHandler({HttpMessageNotReadableException.class})
    public Object handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        e.printStackTrace();
        return Result.error(ResponseEnum.ILLEGAL_OPERATION);
    }

    @ExceptionHandler
    public Object handleException(MethodArgumentNotValidException e, BindingResult errors) {
        e.printStackTrace();
        List<String> collect = errors.getFieldErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.toList());
        return Result.error(ResponseEnum.ILLEGAL_OPERATION, collect);
    }
}